package sale.wxb.loveshopping.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import sale.wxb.loveshopping.entity.model.SysUser;
import sale.wxb.loveshopping.utils.SecurityUtil;

import java.time.LocalDateTime;

@Configuration
public class MPConfig implements MetaObjectHandler {
    /**
     * 插件配置
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 乐观锁插件
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        // 添加防全表更新，删除插件
        interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
        // 添加分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    /**
     * 插入时自动填充
     * @param metaObject MetaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        setFill(metaObject, "createTime", "createUser");
    }

    /**
     * 更新时自动填充
     * @param metaObject MetaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        setFill(metaObject, "updateTime", "updateUser");
    }

    private void setFill(MetaObject metaObject, String time, String user) {
        // strictInsertFill 貌似存在BUG 无法填充第二行更换方法使用
        SysUser sysUser = SecurityUtil.securityContextHolderGetSysUser();
        this.setFieldValByName(time, LocalDateTime.now(), metaObject);
        this.setFieldValByName(user, sysUser.getAccount(), metaObject);
    }
}
